package com.campus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.common.core.domain.AjaxResult;
import com.campus.common.utils.bean.BeanUtils;
import com.campus.mapper.ArticleMapper;
import com.campus.pojos.domain.ClientArticle;
import com.campus.pojos.domain.ClientArticleLove;
import com.campus.pojos.domain.dto.AdminArticlePageQueryDTO;
import com.campus.pojos.domain.dto.ArticleDto;
import com.campus.pojos.domain.dto.ArticleQueryDto;
import com.campus.pojos.domain.dto.PageQueryDto;
import com.campus.pojos.domain.vo.ArticleVo;
import com.campus.result.PageResult;
import com.campus.result.Result;
import com.campus.service.ArticleLoveService;
import com.campus.service.ArticleService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, ClientArticle> implements ArticleService {


    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    private ArticleLoveService articleLoveService;
    /**
     * 保存帖子
     *
     * @param dto
     */
    @Override
    public void saveArticle(ArticleDto dto) {
        if(dto == null){
            log.error("帖子为null, 保存失败");
            return;
        }
        ClientArticle article = new ClientArticle();
        BeanUtils.copyProperties(dto, article);
        //补充字段
        //状态默认为审核中
        article.setStatus(0);
        //点赞数默认为0
        article.setLove(0L);

        if(dto.getContentImages()!=null)
        {
            //图片资源特殊处理
            List<String> images = dto.getContentImages();
            //多个图片之间用,拼接
            String imagesStr = images.stream().map(String::valueOf).collect(Collectors.joining(","));
            article.setContentImage(imagesStr);
        }
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());

        save(article);
    }

    /**
     * 按条件获取贴子列表
     *
     * @param dto
     * @return
     */
    @Override
    public Result<List<ArticleVo>> articleList(ArticleQueryDto dto) {
        //参数验证
        if(dto == null){
            return Result.error("dto为空");
        }

        QueryWrapper<ClientArticle> qw = new QueryWrapper<>();

        //墙分类id
        if(dto.getCategoryId() != null){
            qw.eq("category_id" ,dto.getCategoryId());
        }
        //搜索内容
        if(!StringUtils.isBlank(dto.getSearch())){
            qw.like("title", dto.getSearch()).or().like("content_context", dto.getSearch());
        }
        //用户id
        if(dto.getUserId() != null){
            qw.eq("user_id", dto.getUserId());
        }

        //判断type (0.按时间倒叙， 1.按热度倒叙)
        if(dto.getType() == 0){
            qw.orderByDesc("create_time");
        }else{
            qw.orderByDesc("love");
        }
        //只返回审核通过的
        //qw.eq("status", 1);

        List<ClientArticle> list = list(qw);

        //处理结果返回
        List<ArticleVo> listVo = getArticleVos(list);
        return Result.success(listVo);
    }

    /**
     * 根据id查询帖子
     *
     * @param id
     * @return
     */
    @Override
    public Result<ArticleVo> getByArticleId(Long id) {
        ClientArticle article = getById(id);
        if(article == null) {
            log.error("未查到id为{}的帖子",id);
            return  Result.error("id有误!");
        }
        //返回结果
        return Result.success(getArticleVo(article));
    }

    /**
     * 根据id查询帖子
     *
     * @param id
     * @return
     */
    @Override
    public AjaxResult getByArticleIdTwo(Long id) {
        ClientArticle article = getById(id);
        if(article == null) {
            log.error("未查到id为{}的帖子",id);
            return  AjaxResult.error("id有误!");
        }
        //返回结果
        return AjaxResult.success("success",getArticleVo(article));
    }

    /**
     * 获取ArticleVos
     * @param list
     */
    private List<ArticleVo> getArticleVos(List<ClientArticle> list) {
        List<ArticleVo> articleVos = new ArrayList<>();
        for(ClientArticle article : list){
            ArticleVo articleVo = getArticleVo(article);
            //存入articleVos中
            articleVos.add(articleVo);
        }
        //返回结果
        return articleVos;
    }

    /**
     * 将文章实体类转成文章Vo
     * @param article
     * @return
     */

    private static ArticleVo getArticleVo(ClientArticle article) {
        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article, articleVo);
        //特殊处理图片url
        if(!StringUtils.isBlank(article.getContentImage())) {
            String imageStr = article.getContentImage();
            //stream 将String转成List
            List<String> imageList = Arrays.stream(imageStr.split(",")).collect(Collectors.toList());
            articleVo.setContentImage(imageList);
        }
        return articleVo;
    }

    /**
     * 编辑帖子
     * @param dto
     * @return
     */
    public void editArticle(ArticleDto dto) {
        if (dto==null)
        {
            log.error("帖子为null, 保存失败");
            return;
        }
        ClientArticle article = new ClientArticle();
        BeanUtils.copyProperties(dto, article);
        //补充字段
        //状态默认为审核中
        //article.setStatus(1);
        article.setId(dto.getArticleId());
        if(dto.getContentImages()!=null && !dto.getContentImages().isEmpty())
        {
            //图片资源特殊处理
            List<String> images = dto.getContentImages();
            //多个图片之间用,拼接
            String imagesStr = images.stream().map(String::valueOf).collect(Collectors.joining(","));
            article.setContentImage(imagesStr);
        }
        article.setUpdateTime(LocalDateTime.now());

        articleMapper.edit(article);
    }

    /**
     * 点赞
     * @param articleId
     */
    @Override
    public void likeArticle(Long articleId, Long userId) {

        ClientArticle article = getById(articleId);
        if(article == null){
            log.error("帖子不存在");
            return;
        }

        ClientArticleLove clientArticleLove = new ClientArticleLove();
        clientArticleLove.setArticleId(articleId);
        clientArticleLove.setUserId(userId);
        //存储帖子用户点赞关系
        articleLoveService.save(clientArticleLove);

        //点赞数加1
        article.setLove(article.getLove() + 1);
        updateById(article);
    }

    /**
     * 取消点赞
     *
     * @param articleId
     * @param userId
     */
    @Override
    public void dislikeArticle(Long articleId, Long userId) {
        ClientArticle article = getById(articleId);
        //验证参数
        if(article == null){
            log.error("帖子不存在");
            return;
        }
        //删除帖子用户点赞关系
        Map<String, Object> map = new HashMap<>();
        map.put("article_id", articleId);
        map.put("user_id", userId);

        articleLoveService.removeByMap(map);

        //点赞数减1
        article.setLove(article.getLove() - 1);
        updateById(article);
    }

    /**
     * 管理端帖子条件查询
     * @param dto
     * @return
     */
    public PageResult conditionSearch(AdminArticlePageQueryDTO dto) {
        if(dto.getPage() == null) dto.setPage(1);
        if(dto.getPageSize() == null) dto.setPageSize(10);
        //开启分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<ClientArticle> page = articleMapper.pageQuery(dto);
        //返回结果
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 帖子状态修改
     * @param articleId
     * @param status
     */
    public void updateStatus(Integer articleId, Integer status) {
        ClientArticle article = getById(articleId);
        article.setStatus(status);
        updateById(article);
    }

    /**
     * 获取有图片的帖子
     */
    @Override
    public Result<PageResult> getPhotoArticle(PageQueryDto dto) {
        if(dto.getPage() == null) dto.setPage(1);
        if(dto.getPageSize() == null) dto.setPageSize(10);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<ClientArticle> page =
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(dto.getPage(), dto.getPageSize());

        QueryWrapper<ClientArticle> qw = new QueryWrapper<>();
        qw.ne("content_image", "");
        qw.orderByDesc("create_time");
        qw.eq("status",1);
        page = articleMapper.selectPage(page,  qw);

        return Result.success(new PageResult(page.getTotal(), page.getRecords()));
    }
}
